
const esprima = require('esprima') // 将源代码转为语法树
const ESTraverse = require('estraverse') // 遍历语法树
const esCodeGen = require('escodegen')  // 将语法树重新生成源代码

const code = `function ast(){}`

const ast = esprima.parse(code); // ast 是以深度优先的原则进行遍历
let indent = 0
const padding = () => ' '.repeat(indent)


ESTraverse.traverse(ast, {
    enter(node) {
        console.log(padding() + node.type + '进入')
        indent += 2
        if (node.type === 'FunctionDeclaration') {
            node.id.name = 'newAst'
        }
    },
    leave(node) {
        indent -= 2
        console.log(padding() + node.type + '离开')
    }
})

const result = esCodeGen.generate(ast)
console.log(result)